﻿//using GalaSoft.MvvmLight;
//using GalaSoft.MvvmLight.Command;
using MSL.Tool;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows.Input;
using System.Windows.Threading;
using TimedTask.Core;
using TimedTask.Enums;
using TimedTask.Models;
using TimedTask.Tools;

//----------------------------------------------------------------*/
// 版权所有：
// 文 件 名：PageFileDownViewModel.cs
// 功能描述：
// 创建标识：m.sh.lin0328@163.com 2014/8/30 14:31:07
// 修改描述：
//----------------------------------------------------------------*/
namespace TimedTask.ViewModel
{
    public class PageFileDownViewModel : BaseViewModel
    {
        private static DispatcherTimer timer;
        private static DownFileTask downTask;
        /// <summary>
        /// 初始化 PageFileDownViewModel
        /// </summary>
        public PageFileDownViewModel()
        {
            this.Suffix = Const.FileSuffix[fileType].ToString();
            this.ButtonEnabled = true;
            this.TextChanged = new BaseCommand((Object m) =>
            {
                this.StatusInfo = "";
            });
            timer = ATimer.setInterval(1000, () =>
            {
                this.Speed = Helper.NetSpeedFormat(DownFileTask.DownloadedBytes); //(int)(DownFileTask.DownloadedBytes / 1024f) + "K/s";
                DownFileTask.DownloadedBytes = 0;
            });
        }
        /// <summary>
        /// 重置
        /// </summary>
        public static void Reset()
        {
            //结束未完成的下载
            if (downTask != null)
                downTask.Cancel = true;

            _IsLoading = false;
            _ButtonEnabled = true;
            _StatusInfo = "";
            _Speed = "0K/s";
        }
        #region 属性

        private static string _StatusInfo = "注：可自定义下载文件后缀，格式为：jpg|png|bmp";
        private string _Suffix;
        private static bool _ButtonEnabled;
        private static string _Speed;//下载速度 
        private static bool _IsLoading = false;

        private FileType fileType = FileType.IMAGE;

        /// <summary> 是否显示进度条 </summary>
        public bool IsLoading
        {
            get { return _IsLoading; }
            set
            {
                base.SetProperty<bool>(ref _IsLoading, value);
            }
        }
        /// <summary> 下载速度 </summary>
        public string Speed
        {
            get { return _Speed; }
            set
            {
                base.SetProperty<string>(ref _Speed, value);
            }
        }
        /// <summary> 按钮是否可用 </summary>
        public bool ButtonEnabled
        {
            get { return _ButtonEnabled; }
            set
            {
                base.SetProperty<bool>(ref _ButtonEnabled, value);
            }
        }
        /// <summary> 文件后缀 </summary>
        public string Suffix
        {
            get { return _Suffix; }
            set
            {
                base.SetProperty<string>(ref this._Suffix, value);
            }
        }

        /// <summary> 状态栏信息 </summary>
        public string StatusInfo
        {
            get { return _StatusInfo; }
            set
            {
                base.SetProperty<string>(ref _StatusInfo, value);
            }
        }
        #endregion

        #region 命令

        private ICommand _IamgeDownCommand;
        private ICommand _FileTypeChangedCommand;

        /// <summary> 文本变化命令 </summary>
        public ICommand TextChanged { get; set; }
        public ICommand FileTypeChangedCommand
        {
            get
            {
                if (_FileTypeChangedCommand == null)
                {
                    _FileTypeChangedCommand = new BaseCommand((Object val) =>
                    {
                        foreach (FileType type in Enum.GetValues(typeof(FileType)))
                        {
                            if ((int)type == Convert.ToInt32(val.ToString()))
                            {
                                fileType = type;
                                this.Suffix = Const.FileSuffix[fileType].ToString();
                                if (type.Equals(FileType.CUSTOM))
                                {
                                    this.StatusInfo = "注：可自定义下载文件后缀，格式为：txt|doc|pdf";
                                }
                                break;
                            }
                        }
                    });
                }
                return _FileTypeChangedCommand;
            }
        }
        /// <summary> 下载命令 </summary>
        public ICommand ImageDownCommand
        {
            get
            {
                if (_IamgeDownCommand == null)
                {
                    _IamgeDownCommand = new BaseCommand((Object obj) =>
                    {
                        string url = Convert.ToString(obj);
                        if (String.IsNullOrEmpty(url))
                        {
                            this.StatusInfo = "网址不能为空！";
                            return;
                        }
                        if (!url.StartsWith("http"))
                        {
                            this.StatusInfo = "请输入正确的网址！";
                            return;
                        }
                        if (String.IsNullOrEmpty(this.Suffix))
                        {
                            this.StatusInfo = "文件类型不能为空！";
                            return;
                        }
                        this.ButtonEnabled = false;
                        this.IsLoading = true;
                        DoDownFile(url);
                    });
                }
                return _IamgeDownCommand;
            }
        }
        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <param name="url"></param>
        private void DoDownFile(string url)
        {
            string html = String.Empty;//
            List<string> list = null;

            this.IsLoading = true;
            #region 取 html
            try
            {
                html = HtmlHelper.GetHtml(url);
                html = HtmlHelper.FixUrl(url, html);
            }
            catch (Exception ex)
            {
                LogHelper.SaveErrorLog("ViewModel PageIamgeDownViewModel DoDownFile url[" + url + "]", ex);
                return;
            }

            #endregion

            switch (fileType)
            {
                case FileType.IMAGE:
                    list = HtmlHelper.GetImages(html, this.Suffix);
                    break;
                default:
                    list = HtmlHelper.GetFiles(html, this.Suffix);
                    break;
            }
            string savePath = Models.Const.StartPath + "\\Down\\" + fileType.ToString().ToLower() + "\\";

            MSL.Tool.IOHelper.DeleteFolder(savePath);
            MSL.Tool.IOHelper.CreateFolder(savePath);

            DoDownWork(list, savePath);
        }
        /// <summary>
        /// 多线程下载文件
        /// </summary>
        /// <param name="url"></param>
        /// <param name="pageEncode"></param>
        private void DoDownWork(List<string> list, string savePath)
        {
            if (list != null && list.Count > 0)
            {
                DateTime beforDT = DateTime.Now;

                downTask = new DownFileTask(list);
                DownFileTask.SavePath = savePath;
                downTask.ThreadCount = 10;//开启线程
                downTask.OneCompleted += (s, arg) =>
                {
                    this.StatusInfo = "共有文件链接" + list.Count + "个，下载成功" + DownFileTask.YesNum + ",失败" + DownFileTask.NoNum + "";
                };
                downTask.AllCompleted += (BaskTask<string>.CompetedEventArgs obj) =>
                {
                    TimeSpan ts = DateTime.Now.Subtract(beforDT);
                    this.StatusInfo = "共有文件链接" + list.Count + "个，下载成功" + DownFileTask.YesNum + ",失败" + DownFileTask.NoNum + "";
                    this.StatusInfo += String.Format("共花费{0}s.",
                        String.Format("{0:F}", ts.TotalMilliseconds / 1000));

                    System.Diagnostics.Process.Start("explorer.exe", savePath);
                    this.IsLoading = false;
                    this.ButtonEnabled = true;
                };
                downTask.Start();
            }
            else
            {
                this.StatusInfo = "没有发现文件链接的存在！";
                this.IsLoading = false;
                this.ButtonEnabled = true;
            }
        }
    }
}
